package com.lson.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.bcel.classfile.Constant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;

@RestController
@RequestMapping("/test")
public class TestController {
    @RequestMapping("/gate")
    public Object test() throws Exception{
        Thread.sleep(5000);
        System.out.println(1111);
        a();
        return "success";
    }

    public void a(){

    }

    public static void main(String[] args) {
        String fileUrl ="/Users/lixuejie/Documents/workspace/test/test.csv";
        try {
            File file = new File(fileUrl);
            FileBody filebody = new FileBody(file,  ContentType.create("text/cvs","utf-8"), "file");
            //转换成文件流
//            InputStream is = new URL(fileUrl).openStream();

            //接收文件的服务器地址
            String uploadURL = "https://www.baidu.com";

            //创建HttpClient
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(uploadURL);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.seContentType(ContentType.MULTIPART_FORM_DATA);
            /*绑定文件参数，传入文件流和contenttype，此处也可以继续添加其他formdata参数*/
            builder.addPart("file",filebody);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            //执行提交
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity != null) {
                //将响应的内容转换成字符串
                String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));

                //此处根据服务器返回的参数转换，这里返回的是JSON格式
                JSONObject output = JSON.parseObject(result);
                JSONArray body = output.getJSONArray("body");
                String resUrl = body.get(0) + "";

                System.out.println(resUrl);
            }

        }catch (Exception ex){
            ex.printStackTrace();
        }


    }
}
